package com.ycsj.goldmedalnewconcept.activity;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.mob.tools.utils.UIHandler;
import com.squareup.okhttp.Call;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import com.ycsj.goldmedalnewconcept.R;
import com.ycsj.goldmedalnewconcept.adapter.WorkSutdentGvAdapter;
import com.ycsj.goldmedalnewconcept.bean.HomeworkResponse;
import com.ycsj.goldmedalnewconcept.bean.WorkInfo;
import com.ycsj.goldmedalnewconcept.constant.Constant;
import com.ycsj.goldmedalnewconcept.utils.Bimp;
import com.ycsj.goldmedalnewconcept.utils.FileUtils;
import com.ycsj.goldmedalnewconcept.utils.GsonUtil;
import com.ycsj.goldmedalnewconcept.utils.ImageItem;
import com.ycsj.goldmedalnewconcept.utils.PublicWay;
import com.ycsj.goldmedalnewconcept.utils.Res;
import com.ycsj.goldmedalnewconcept.utils.SPUtil;
import com.ycsj.goldmedalnewconcept.utils.ShowKeyboardUtils;
import com.ycsj.goldmedalnewconcept.utils.UiHelper;
import com.ycsj.goldmedalnewconcept.view.MyGridView;

import ct.bu;

/**
 * 创建日期：2017/12/6 9:27 描述:布置作业 作者:张伟
 */

@SuppressLint("NewApi")
public class BabyWorkActivity extends Activity implements OnClickListener {

	// 返回按钮
	private LinearLayout llBack,llMain;

	// 标题右边跳转到作业详情
	private RelativeLayout rlDetails;

	// 内容详情
	private LinearLayout llDetails;

	// 加载中视图
	private LinearLayout llLoading;

	// 显示打开列表的TextView
	private TextView tvShow;

	// 显示学生列表的MyGridView
	private MyGridView gvStudents;

	// 显示打开列表和关闭列表的线性布局
	private LinearLayout llShow;

	// 底部的提交和取消按钮
	private Button btComit, btCancel;

	// 显示上次和本次点评作业的TextView
	private TextView tv_showlastnum, tv_showthisnum;

	// 上次作业
	private EditText etLastWork;

	// 本次作业
	private EditText etNewWork;

	// 显示选择图片的GridView
	private MyGridView gvShowPic;

	// 上个页面传递过来的num;
	private String num;

	// 展示学生的数据集合
	private List<WorkInfo.ListBean> oldDatas;

	// 选中的学生数据集合
	private List<WorkInfo.ListBean> selectStudentList;

	// 初次从服务器请求的学生的全部数据
	private List<WorkInfo.ListBean> newDatas;

	// 显示从服务器返回的学生列表GridView
	private WorkSutdentGvAdapter mgvAdapter;

	// 用于显示从系统图库选择相片的GridView
	// private GvPicAdapter picAdapter;
	private GridAdapter adapter;

	// 用于构建选中学生的字符串
	private String selectStudentJson;

	// 上次点评的作业情况
	private String lastContent;

	// 布置的本次作业
	private String newContent;

	// 用于记录相册选择的图片地址
	private List<String> mPaths;

	public static Bitmap bimap;

	private HttpUtils httpUtils;

	private RequestParams params;

	public static String SDPATH = Environment.getExternalStorageDirectory()
			+ "/Photo_LJ/";

	private File f;

	@Override
	protected void onCreate(@Nullable Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_baby_work);
		Res.init(this);

		// 设置状态栏
		setBar();

		// 获取传递过来的classId
		getData();

		// 初始化View
		initView();
		
		// 初始化底部弹窗的PopUpwindow
		intPop();

		// 设置监听
		initListener();

		// 设置展示学生的GridView适配器
		initMgv();

		// 设置选择相册图片的GridView
		initPic();

		// 请求服务器数据
		http();
	}

	private PopupWindow pop;
	private LinearLayout ll_popup;

	private String ttel;

	private String class_id;

	private String account;

	private String role;

	private String url;

	private static final int TAKE_PICTURE = 0x000001;

	protected void onRestart() {
		adapter.update();
		super.onRestart();
	}

	@Override
	protected void onDestroy() {
		for (int i = 0; i < PublicWay.activityList.size(); i++) {
			if (null != PublicWay.activityList.get(i)) {
				PublicWay.activityList.get(i).finish();
			}
		}

		bimap = null;
		System.gc();

		Bimp.tempSelectBitmap.clear();
		Bimp.max = 0;
		Intent intent = new Intent("data.broadcast.action");
		sendBroadcast(intent);

		super.onDestroy();
	}

	/**
	 * 初始化底部弹框的代码
	 */
	private void intPop() {
		pop = new PopupWindow(this);
		View view = getLayoutInflater().inflate(R.layout.item_popupwindows,
				null);
		ll_popup = (LinearLayout) view.findViewById(R.id.ll_popup);
		pop.setWidth(LayoutParams.MATCH_PARENT);
		pop.setHeight(LayoutParams.WRAP_CONTENT);
		pop.setBackgroundDrawable(new BitmapDrawable());
		pop.setFocusable(true);
		pop.setOutsideTouchable(true);
		pop.setContentView(view);
		RelativeLayout parent = (RelativeLayout) view.findViewById(R.id.parent);
		Button bt1 = (Button) view.findViewById(R.id.item_popupwindows_camera);
		Button bt2 = (Button) view.findViewById(R.id.item_popupwindows_Photo);
		Button bt3 = (Button) view.findViewById(R.id.item_popupwindows_cancel);

		parent.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				pop.dismiss();
				ll_popup.clearAnimation();
			}
		});

		bt1.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				photo();
				pop.dismiss();
				ll_popup.clearAnimation();
			}
		});

		bt2.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				Intent intent = new Intent(BabyWorkActivity.this,
						AlbumActivity.class);
				startActivity(intent);
				overridePendingTransition(R.anim.activity_translate_in,
						R.anim.activity_translate_out);
				pop.dismiss();
				ll_popup.clearAnimation();
			}
		});

		bt3.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				pop.dismiss();
				ll_popup.clearAnimation();
			}
		});
	}

	/**
	 * 跳转到系统相册的方法
	 */
	public void photo() {
		Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		startActivityForResult(openCameraIntent, TAKE_PICTURE);
	}

	/**
	 * 选择系统拍照的回调方法
	 */
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		case TAKE_PICTURE:
			if (Bimp.tempSelectBitmap.size() < 9 && resultCode == RESULT_OK) {

				String fileName = String.valueOf(System.currentTimeMillis());
				Bitmap bm = (Bitmap) data.getExtras().get("data");
				FileUtils.saveBitmap(bm, fileName);

				ImageItem takePhoto = new ImageItem();
				takePhoto.setBitmap(bm);
				takePhoto.setImagePath(Environment
						.getExternalStorageDirectory()
						+ "/Photo_LJ/"
						+ fileName + ".png");
				Bimp.tempSelectBitmap.add(takePhoto);
			}
			break;
		}
	}

	/**
	 * 初始化View的方法
	 */
	private void initView() {
		llBack = (LinearLayout) findViewById(R.id.ll_back);
		rlDetails = (RelativeLayout) findViewById(R.id.rl_deatail);
		llShow = (LinearLayout) findViewById(R.id.ll_show);
		tvShow = (TextView) findViewById(R.id.tv_show);
		etLastWork = (EditText) findViewById(R.id.et_last_work);
		etNewWork = (EditText) findViewById(R.id.et_new_work);
		gvStudents = (MyGridView) findViewById(R.id.mgv);
		gvShowPic = (MyGridView) findViewById(R.id.gv_show_pic);
		llLoading = (LinearLayout) findViewById(R.id.ll_loading);
		llDetails = (LinearLayout) findViewById(R.id.ll_details);
		btComit = (Button) findViewById(R.id.bt_comit);
		btCancel = (Button) findViewById(R.id.bt_cancel);
		tv_showlastnum = (TextView) findViewById(R.id.tv_showlastnum);
		tv_showthisnum = (TextView) findViewById(R.id.tv_showthisnum);
		llMain=(LinearLayout) findViewById(R.id.ll_main);
		
		new ShowKeyboardUtils().controlKeyboardLayout(llMain, etNewWork, this);
		
		oldDatas = new ArrayList<>();
	}

	/**
	 * 获取传递的classId
	 */
	public void getData() {
		num = getIntent().getStringExtra("num");
		class_id = getIntent().getStringExtra("class_id");
		ttel = getIntent().getStringExtra("ttel");
		num = getIntent().getStringExtra("num");
		account = SPUtil.getString(this, "account", "");
		role = SPUtil.getString(this, "role", "");
	}

	/**
	 * 请求页面学生数据
	 */
	private void http() {
		OkHttpClient mOkHttpClient = new OkHttpClient();
		FormEncodingBuilder builder = new FormEncodingBuilder();
		builder.add("type", "2");
		builder.add("platform", "2");
		builder.add("ttel", ttel);
		builder.add("num", num);
		Request request = new Request.Builder()
				.url(Constant.ycsj_count_MessageCenter)
				// .url("http://m.moregolden.com/ycsj_count/MessageCenter")
				.post(builder.build()).build();
		mOkHttpClient.newCall(request).enqueue(new Callback() {
			@Override
			public void onFailure(Request request, IOException e) {
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						// 请求失败,主线程更新UI操作
						if (llLoading != null) {
							llLoading.setVisibility(View.GONE);
						}
						Toast.makeText(BabyWorkActivity.this, "网络错误",
								Toast.LENGTH_SHORT).show();
					}
				});
			}

			@Override
			public void onResponse(Response response) throws IOException {
				try {
					// 获取服务器返回的json数据
					String json = response.body().string();
					Log.i("test", "获取的的json值是:" + json);
					WorkInfo info = GsonUtil.jsonToBean(json, WorkInfo.class);
					if (1 == info.getState()) {
						// 返回成功
						newDatas = info.getList();
						if (newDatas == null || newDatas.size() == 0) {
							// 证明没有数据
							// 证明返回错误
							runOnUiThread(new Runnable() {
								@Override
								public void run() {
									// 请求失败,主线程更新UI操作
									if (llLoading != null) {
										llLoading.setVisibility(View.GONE);
									}

									Builder builder = new Builder(
											BabyWorkActivity.this);
									builder.setTitle("提示");
									builder.setMessage("该班级暂无学生可以布置作业");
									builder.setCancelable(false);
									builder.setPositiveButton(
											"确定",
											new DialogInterface.OnClickListener() {
												@Override
												public void onClick(
														DialogInterface dialog,
														int which) {
													finish();
												}
											});
									builder.show();
								}
							});
						} else {
							runOnUiThread(new Runnable() {
								@Override
								public void run() {
									// 隐藏加载布局,显示内容布局
									if (llLoading != null) {
										llLoading.setVisibility(View.GONE);
									}

									if (llDetails != null) {
										llDetails.setVisibility(View.VISIBLE);
									}

									// 证明有数据
									if (newDatas.size() < 4) {
										// 如果少于4个学生不需要显示打开列表的提醒按钮
										llShow.setVisibility(View.GONE);
										// 小于4个的时候将数据全部添加到oldDatas中
										oldDatas.addAll(newDatas);
									} else {
										// 返回的学生大于4个则显示打开里列表的提醒按钮
										llShow.setVisibility(View.VISIBLE);
										for (int i = 0; i < 4; i++) {
											oldDatas.add(newDatas.get(i));
										}
									}
									// 通知适配器刷新数据
									mgvAdapter.notifyDataSetChanged();
								}
							});
						}

					} else {
						// 证明返回错误
						runOnUiThread(new Runnable() {
							@Override
							public void run() {
								// 请求失败,主线程更新UI操作
								if (llLoading != null) {
									llLoading.setVisibility(View.GONE);
								}
								Toast.makeText(BabyWorkActivity.this, "网络错误",
										Toast.LENGTH_SHORT).show();
							}
						});
					}

				} catch (Exception e) {
					Log.i("test", e.toString());
				}
			}
		});
	}

	/**
	 * 设置监听的方法
	 */
	private void initListener() {
		llBack.setOnClickListener(this);
		rlDetails.setOnClickListener(this);
		tvShow.setOnClickListener(this);
		btComit.setOnClickListener(this);
		btCancel.setOnClickListener(this);
		etLastWork.addTextChangedListener(new LastWatcher());
		etNewWork.addTextChangedListener(new ThisWatcher());
	}

	/**
	 * 上次作业点评的EidtText的输入监听事件
	 * 
	 * @author Administrator
	 *
	 */
	class LastWatcher implements TextWatcher {

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {

		}

		@Override
		public void onTextChanged(CharSequence s, int start, int before,
				int count) {

		}

		@Override
		public void afterTextChanged(Editable s) {
			String text = etLastWork.getText().toString().trim();
			if (TextUtils.isEmpty(text)) {
				tv_showlastnum.setText("0/200");
			} else {
				tv_showlastnum.setText(text.length() + "/200");
			}
		}

	}

	/**
	 * 本次作业点评的EidtText的输入监听事件
	 * 
	 * @author Administrator
	 *
	 */
	class ThisWatcher implements TextWatcher {

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {

		}

		@Override
		public void onTextChanged(CharSequence s, int start, int before,
				int count) {

		}

		@Override
		public void afterTextChanged(Editable s) {
			String text = etNewWork.getText().toString().trim();
			if (TextUtils.isEmpty(text)) {
				tv_showthisnum.setText("0/200");
			} else {
				tv_showthisnum.setText(text.length() + "/200");
			}
		}

	}

	/**
	 * 设置展示学生的MyGridView的适配器
	 */
	private void initMgv() {
		mgvAdapter = new WorkSutdentGvAdapter(this, oldDatas,
				R.layout.item_gb_students);
		gvStudents.setAdapter(mgvAdapter);
	}

	/**
	 * 显示相册图片的GridView
	 */
	private void initPic() {
		// mPaths = new ArrayList<>();
		// mPaths.add("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1512553195221&di=01fa5b64d12a5b6cca3fe595253e6e01&imgtype=jpg&src=http%3A%2F%2Fimg2.imgtn.bdimg.com%2Fit%2Fu%3D4026424687%2C2740477769%26fm%3D214%26gp%3D0.jpg");
		// mPaths.add("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1512553195221&di=01fa5b64d12a5b6cca3fe595253e6e01&imgtype=jpg&src=http%3A%2F%2Fimg2.imgtn.bdimg.com%2Fit%2Fu%3D4026424687%2C2740477769%26fm%3D214%26gp%3D0.jpg");
		// picAdapter = new GvPicAdapter(this, mPaths);
		// gvShowPic.setAdapter(picAdapter);

		gvShowPic.setSelector(new ColorDrawable(Color.TRANSPARENT));
		adapter = new GridAdapter(this);

		adapter.update();
		gvShowPic.setAdapter(adapter);
		gvShowPic.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				if (arg2 == Bimp.tempSelectBitmap.size()) {

					ll_popup.startAnimation(AnimationUtils
							.loadAnimation(BabyWorkActivity.this,
									R.anim.activity_translate_in));
					pop.showAtLocation(getWindow().getDecorView(),
							Gravity.BOTTOM, 0, 0);

					InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
					if (imm != null) {
						imm.hideSoftInputFromWindow(getWindow().getDecorView()
								.getWindowToken(), 0);
					}

				} else {
					Intent intent = new Intent(BabyWorkActivity.this,
							GalleryActivity.class);
					intent.putExtra("position", "1");
					intent.putExtra("ID", arg2);
					startActivity(intent);
				}
			}
		});

	}

	/**
	 * 显示相册选择图片的GridView适配器
	 * 
	 * @author Administrator
	 *
	 */
	@SuppressLint("HandlerLeak")
	public class GridAdapter extends BaseAdapter {
		private LayoutInflater inflater;
		private int selectedPosition = -1;
		private boolean shape;

		public boolean isShape() {
			return shape;
		}

		public void setShape(boolean shape) {
			this.shape = shape;
		}

		public GridAdapter(Context context) {
			inflater = LayoutInflater.from(context);
		}

		public void update() {
			loading();
		}

		public int getCount() {
			if (Bimp.tempSelectBitmap.size() == 9) {
				return 9;
			}
			return (Bimp.tempSelectBitmap.size() + 1);
		}

		public Object getItem(int arg0) {
			return null;
		}

		public long getItemId(int arg0) {
			return 0;
		}

		public void setSelectedPosition(int position) {
			selectedPosition = position;
		}

		public int getSelectedPosition() {
			return selectedPosition;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder = null;
			if (convertView == null) {
				convertView = inflater.inflate(R.layout.item_published_grida,
						parent, false);
				holder = new ViewHolder();
				holder.image = (ImageView) convertView
						.findViewById(R.id.item_grida_image);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}

			if (position == Bimp.tempSelectBitmap.size()) {
				holder.image.setImageBitmap(BitmapFactory.decodeResource(
						getResources(), R.drawable.icon_addpic_unfocused));
				if (position == 9) {
					holder.image.setVisibility(View.GONE);
				}
			} else {
				holder.image.setImageBitmap(Bimp.tempSelectBitmap.get(position)
						.getBitmap());
			}

			return convertView;
		}

		public class ViewHolder {
			public ImageView image;
		}

		Handler handler = new Handler() {
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case 1:
					adapter.notifyDataSetChanged();
					break;
				}
				super.handleMessage(msg);
			}
		};

		public void loading() {
			new Thread(new Runnable() {
				public void run() {
					while (true) {
						if (Bimp.max == Bimp.tempSelectBitmap.size()) {
							Message message = new Message();
							message.what = 1;
							handler.sendMessage(message);
							break;
						} else {
							Bimp.max += 1;
							Message message = new Message();
							message.what = 1;
							handler.sendMessage(message);
						}
					}
				}
			}).start();
		}
	}

	/**
	 * 页面控件点击事件
	 *
	 * @param view
	 */
	@Override
	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.ll_back:
			// 返回按钮
			finish();
			break;
		case R.id.rl_deatail:
			// 标题栏右边的图标
			Intent intent = new Intent(this, HomeWorkHistoryActivity.class);
			intent.putExtra("class_id", class_id);
			startActivity(intent);
			break;
		case R.id.tv_show:
			// 点击打开列表
			if ("打开列表".equals(tvShow.getText())) {
				// GridView显示全部学生数据
				oldDatas.clear();
				oldDatas.addAll(newDatas);
				mgvAdapter.notifyDataSetChanged();
				tvShow.setText("关闭列表");
			} else if ("关闭列表".equals(tvShow.getText())) {
				// GridView只显示4条数据
				oldDatas.clear();
				for (int i = 0; i < 4; i++) {
					oldDatas.add(newDatas.get(i));
				}
				mgvAdapter.notifyDataSetChanged();
				tvShow.setText("打开列表");
			}
			break;
		case R.id.bt_comit:
			// 提交
			commit();
			break;
		case R.id.bt_cancel:
			// 取消
			finish();
			break;
		}
	}

	/**
	 * 点击提交按钮后需要做的操作 1.判断是否选中学生 2.是否点评了上次作业情况 3.是否布置了本次作业 上传服务器
	 *
	 * @return
	 */
	private void commit() {

		if (!isSelect()) {
			Toast.makeText(BabyWorkActivity.this, "请至少选择一个学生",
					Toast.LENGTH_SHORT).show();
			return;
		}

		// 上次作业点评
		lastContent = etLastWork.getText().toString().trim();
		// if (TextUtils.isEmpty(lastContent)) {
		// Toast.makeText(BabyWorkActivity.this, "请对上次作业进行点评",
		// Toast.LENGTH_SHORT).show();
		// return;
		// }

		// 本次作业
		newContent = etNewWork.getText().toString().trim();
		if (TextUtils.isEmpty(newContent)) {
			Toast.makeText(BabyWorkActivity.this, "请布置本次作业", Toast.LENGTH_SHORT)
					.show();
			return;
		}

		selectStudentList = new ArrayList<>();
		for (int i = 0; i < newDatas.size(); i++) {
			if (!newDatas.get(i).isFlag()) {

				WorkInfo.ListBean bean = new WorkInfo.ListBean();
				bean.setIcon(newDatas.get(i).getIcon());
				bean.setName(newDatas.get(i).getName());
				bean.setNickname(newDatas.get(i).getNickname());
				bean.setSttel(newDatas.get(i).getSttel());
				selectStudentList.add(bean);
			}
		}
		Gson gson = new Gson();
		selectStudentJson = gson.toJson(selectStudentList);

		Log.e("StudentJson", "selectStudentJson" + selectStudentJson);
//		llLoading.setVisibility(llLoading.VISIBLE);
		UiHelper.showDialog(this, "上传中");
		
		
		btComit.setClickable(false);

		httpUtils = new HttpUtils();
		url = Constant.SERVER_URL + "ManageMsg";
		// url = "http://192.168.0.198:8888/ycsj_platform/ManageMsg";
		params = new RequestParams();
		params.addBodyParameter("type", "1");
		params.addBodyParameter("c", account);
		params.addBodyParameter("role", role);
		params.addBodyParameter("school", "");
		params.addBodyParameter("userclass", class_id);
		params.addBodyParameter("studentids", selectStudentJson);
		params.addBodyParameter("title", "");
		params.addBodyParameter("content", newContent);
		params.addBodyParameter("comment", lastContent);
		params.addBodyParameter("status", "0");

		for (int i = 0; i < Bimp.tempSelectBitmap.size(); i++) {
			String name = String.valueOf(System.currentTimeMillis()) + i
					+ ".png";
			try {
				f = new File(SDPATH, name);
				if (f.exists()) {
					f.delete();
				}
				FileOutputStream out = new FileOutputStream(f);
				Bimp.tempSelectBitmap.get(i).getBitmap()
						.compress(Bitmap.CompressFormat.PNG, 20, out);
				out.flush();
				out.close();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			params.addBodyParameter(name, f);
		}
		httpUtils.send(HttpMethod.POST, url, params, callBackHeadimg);

	}

	private RequestCallBack<String> callBackHeadimg = new RequestCallBack<String>() {

		@Override
		public void onSuccess(ResponseInfo<String> responseInfo) {

			String json = responseInfo.result;
			Log.e("upload", json);
			Gson gson = new Gson();
			HomeworkResponse fromJson = gson.fromJson(json,
					HomeworkResponse.class);

//			llLoading.setVisibility(llLoading.GONE);
			
			
			btComit.setClickable(true);
			UiHelper.dismissDialog();
			if (fromJson == null) {
				Toast.makeText(getApplicationContext(), "错误，请检查网络是否正常", 0)
						.show();
				
				return;
			}

			if ("1".equals(fromJson.state)) {
				for (int i = 0; i < selectStudentList.size(); i++) {
					pushMsg(selectStudentList.get(i).getSttel());
				}
				
				
				etLastWork.setText("");
				etNewWork.setText("");
				tv_showthisnum.setText("0/200");
				tv_showlastnum.setText("0/200");
				
				
				Toast.makeText(getApplicationContext(), "发布成功", 0).show();
				Intent intent = new Intent(BabyWorkActivity.this,
						HomeWorkHistoryActivity.class);
				intent.putExtra("class_id", class_id);
				startActivity(intent);
//				finish();
			} else {
				Toast.makeText(getApplicationContext(), "上传失败", 0).show();
			}
		}

		@Override
		public void onFailure(HttpException error, String msg) {
//			llLoading.setVisibility(llLoading.GONE);
			UiHelper.dismissDialog();
			
			btComit.setClickable(true);
			Toast.makeText(getBaseContext(), "发布失败，请检查网络连接是否正常", 0).show();
		}
	};

	// 推送
	private void pushMsg(String userid) {
		// TODO Auto-generated method stub
		OkHttpClient mOkHttpClient3 = new OkHttpClient();
		// 创建一个Request
		final Request request3 = new Request.Builder().url(
				Constant.ycsj_count_MessageCenter + "?type=32&alias=" + userid
						+ "1" + "&content=点击查看最新作业" + "&title=收到作业"
						+ "&ptype=1").build();

		// http://www.moregolden.com/ycsj_count/MessageCenter?type=32&alias=182712617791&content=提交的请假申请已批准&title=请假成功了&ptype=1
		Call call3 = mOkHttpClient3.newCall(request3);
		call3.enqueue(callback3);
	}

	Callback callback3 = new Callback() {

		@Override
		public void onResponse(Response arg0) throws IOException {
			// TODO Auto-generated method stub
			String json = arg0.body().string();
			Log.e("jpush", json);
		}

		@Override
		public void onFailure(Request arg0, IOException arg1) {

		}
	};

	/**
	 * 判断老师是否选中了学生的方法 返回值true表示有选择学生,false表示没有选择学生
	 *
	 * @return
	 */
	private boolean isSelect() {
		boolean res = false;
		for (int i = 0; i < oldDatas.size(); i++) {
			if (false == oldDatas.get(i).isFlag()) {
				res = true;
				break;
			}
		}
		return res;
	}

	/**
	 * 设置沉浸状态栏的方法,需要在setContentView()之后调用
	 */
	private void setBar() {
		// 兼容5.0+，状态栏设置透明
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
			Window window = getWindow();
			window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
			window.getDecorView().setSystemUiVisibility(
					View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
							| View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
			window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
			window.setStatusBarColor(Color.TRANSPARENT);
		} else
		// 为了沉浸式状态栏 4.4以上才有
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
			getWindow().addFlags(
					WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
		}
	}
}
